﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using System.Xml;
using Altairis.FluffyCloud.Data;
using Altairis.FluffyCloud.Security;
using Altairis.Web;

namespace Altairis.FluffyCloud.WebCore.Handlers {

    public class TopicFeedHandler : IHttpHandler {

        public bool IsReusable {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context) {
            using (var dc = new FluffyDbContext()) {
                // Get user from security code
                var securityCode = context.Request.RequestContext.RouteData.Values["securityCode"] as string;
                var user = dc.Users.SingleOrDefault(x => x.SecurityCode.Equals(securityCode, StringComparison.Ordinal));
                if (user == null) {
                    // User not found (security code invalid)
                    context.Response.SendErrorResponse(404, "Object Not Found", "Invalid security code");
                    return;
                }

                // Get topic
                var topicId = int.Parse(context.Request.RequestContext.RouteData.Values["topicId"] as string);
                var topic = dc.Topics.SingleOrDefault(x => x.TopicId == topicId);
                if (topic == null || !topic.AccessList.EvaluatePermissions(TopicAclEntry.OperationRead, user.Roles.Select(x => x.RoleName).ToArray())) {
                    // Topic not found or no permissions
                    context.Response.SendErrorResponse(404, "Object Not Found", "Topic not found or no permissions");
                    return;
                }

                // Get posts
                var baseUrl = context.Request.ApplicationBaseUri().ToString() + "forum/" + topic.TopicId;
                var userName = user.UserName;
                var q = from p in topic.Posts
                        orderby p.DateCreated descending
                        select p;
                var items = new List<SyndicationItem>();
                foreach (var p in q) {
                    var item = new SyndicationItem {
                        Content = new TextSyndicationContent(p.Text, TextSyndicationContentKind.Plaintext),
                        PublishDate = p.DateCreated,
                        Title = new TextSyndicationContent(string.Format("Příspěvek od uživatele {0}", p.UserName))
                    };
                    item.AddPermalink(new Uri(string.Format("{0}#{1:N}", baseUrl, p.TopicPostId)));
                    items.Add(item);
                }

                // Create feed header
                var feed = new SyndicationFeed("FluffyCloud: Příspěvky ve fóru " + topic.Name, topic.Description, new Uri(baseUrl), items) {
                    Generator = string.Format("FluffyCloud (www.fluffycloud.cz), {0}", Global.VersionString),
                    Items = items
                };

                // Save as RSS feed
                context.Response.ContentType = "text/xml";
                using (var xw = XmlWriter.Create(context.Response.Output)) {
                    feed.SaveAsRss20(xw);
                }
            }
        }
    }
}